package stpmproject.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import stpmproject.controller.viewobject.TodoVO;
import stpmproject.error.BusinessException;
import stpmproject.error.EmBusinessError;
import stpmproject.response.CommonReturnType;
import stpmproject.service.TodoService;
import stpmproject.service.UserService;
import stpmproject.service.model.TodoModel;
import stpmproject.service.model.UserModel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * encoding: utf-8
 *
 * @Author: kou dui
 * @Date: 2019/5/27 0:06
 * @software: IntelliJ IDEA
 * @file: TodoController
 * @description:
 */
@Controller("todo")
@RequestMapping("/todo")
@CrossOrigin(allowedHeaders = {"*"},allowCredentials = "true") //springboot前端请求的跨域问题
public class TodoController extends BaseController {
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private TodoService todoService;

    @Autowired
    private UserService userService;

    //获取代办列表,开启分页功能
    @RequestMapping(value = "/list",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listTodo(@RequestParam(name = "page") Integer page,
                                     @RequestParam(name = "limit") Integer limit){
        //开启分页
        Page tmpPage=PageHelper.startPage(page,limit);
        List<TodoModel> todoModelList=todoService.listTodo();
        List<TodoVO> todoVOList=todoModelList.stream().map(todoModel -> {
            TodoVO todoVO=this.convertVOFromModel(todoModel);
            return todoVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(todoVOList,tmpPage.getTotal());
    }

    //获取代办列表,开启分页功能
    @RequestMapping(value = "/mytodo",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listMyTodo(@RequestParam(name = "page") Integer page,
                                       @RequestParam(name = "limit") Integer limit,
                                       HttpSession session) throws BusinessException {
        //开启分页
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        Page tmpPage=PageHelper.startPage(page,limit);
        List<TodoModel> todoModelList=null;
        List<TodoVO> todoVOList=null;
        if(userModel!=null) {
            todoModelList = todoService.getTodoByCreater(userModel.getUsername());
            todoVOList=todoModelList.stream().map(todoModel -> {
                TodoVO todoVO = this.convertVOFromModel(todoModel);
                todoVO.setRole(userModel.getRole());
                return todoVO;
            }).collect(Collectors.toList());
        }
        return CommonReturnType.create(todoVOList,tmpPage.getTotal());
    }

    //开始代办事项
    @RequestMapping(value = "/start",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public  CommonReturnType startTodo(@RequestParam(name = "id") Integer todoId,
                                       @RequestParam(name = "todoStartDate") String todoStartDate,
                                       HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TodoModel todoModel=todoService.getTodoById(todoId);
        System.out.println("todoModel.getTodoCreater() = " + todoModel.getTodoCreater());
        if(!todoModel.getTodoCreater().equals(userModel.getUsername())){
            throw new BusinessException(EmBusinessError.START_FAIL);
        }
        todoModel.setTodoStartDate(new DateTime(todoStartDate.replace(" ","T")));
        todoModel.setTodoStatus("进行中");
        todoService.updateTodo(todoModel);
        return CommonReturnType.create(null);
    }
    //完成代办事项
    @RequestMapping(value = "/finish",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public  CommonReturnType finishTodo(@RequestParam(name = "id") Integer todoId,
                                       @RequestParam(name = "todoEndDate") String todoEndDate,
                                        HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TodoModel todoModel=todoService.getTodoById(todoId);
        if(!todoModel.getTodoCreater().equals(userModel.getUsername())){
            throw new BusinessException(EmBusinessError.FINISH_FAIL);
        }
        todoModel.setTodoEndDate(new DateTime(todoEndDate.replace(" ","T")));
        todoModel.setTodoStatus("已完成");
        todoService.updateTodo(todoModel);
        return CommonReturnType.create(null);
    }
    //删除代办事项
    @RequestMapping(value = "/delete",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public  CommonReturnType deleteTodo(@RequestParam(name = "id") Integer todoId,
                                        HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TodoModel todoModel=todoService.getTodoById(todoId);
        if(!todoModel.getTodoCreater().equals(userModel.getUsername())){
            throw new BusinessException(EmBusinessError.DELETE_FAIL_2);
        }
        todoService.deleteTodo(todoId);
        return CommonReturnType.create(null);
    }
    //添加代办事项
    @RequestMapping(value = "/create",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public  CommonReturnType createTodo(@RequestParam(name = "todoName") String todoName,
                                        @RequestParam(name = "todoPriority") String todoPriority,
                                        @RequestParam(name = "todoStartDate") String todoStartDate,
                                        @RequestParam(name = "todoEndDate") String todoEndDate,
                                        @RequestParam(name = "todoDesc") String todoDesc,
                                        @RequestParam(name = "todoCreateDate") String todoCreateDate,
                                        HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TodoModel Model=todoService.getTodoByName(todoName);
        if(Model!=null){
            throw new BusinessException(EmBusinessError.TODO_EXIST);
        }
        TodoModel todoModel=new TodoModel();
        todoModel.setTodoName(todoName);
        todoModel.setTodoPriority(todoPriority);
        todoModel.setTodoDesc(todoDesc);
        todoModel.setTodoCreater(userModel.getUsername());
        todoModel.setTodoStatus("未开始");
        todoModel.setTodoStartDate(new DateTime(todoStartDate.replace(" ","T")));
        todoModel.setTodoEndDate(new DateTime(todoEndDate.replace(" ","T")));
        todoModel.setTodoCreateDate(new DateTime(todoCreateDate.replace(" ","T")));
        todoService.createTodo(todoModel);
        return CommonReturnType.create(null);
    }
    //添加代办事项,编辑和删除代办的时候需要判断当前登录用户是否为创建用户
    @RequestMapping(value = "/update",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public  CommonReturnType updateTodo(@RequestParam(name = "id") Integer todoId,
                                        @RequestParam(name = "todoPriority_edit") String todoPriority,
                                        @RequestParam(name = "todoStartDate_edit") String todoStartDate,
                                        @RequestParam(name = "todoEndDate_edit") String todoEndDate,
                                        @RequestParam(name = "todoDesc_edit") String todoDesc,
                                        @RequestParam(name = "todoCreateDate_edit") String todoCreateDate,
                                        HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        TodoModel Model=todoService.getTodoById(todoId);
        if(!userModel.getUsername().equals(Model.getTodoCreater())){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"你没有修改的权限");
        }
        TodoModel todoModel=new TodoModel();
        todoModel.setId(todoId);
        todoModel.setTodoPriority(todoPriority);
        todoModel.setTodoDesc(todoDesc);
        todoModel.setTodoStartDate(new DateTime(todoStartDate.replace(" ","T")));
        todoModel.setTodoEndDate(new DateTime(todoEndDate.replace(" ","T")));
        todoModel.setTodoCreateDate(new DateTime(todoCreateDate.replace(" ","T")));
        todoService.updateTodo(todoModel);
        return CommonReturnType.create(null);
    }
    private TodoVO convertVOFromModel(TodoModel todoModel){
        if(todoModel==null){
            return null;
        }
        TodoVO todoVO=new TodoVO();
        BeanUtils.copyProperties(todoModel,todoVO);
        todoVO.setTodoStartDate(todoModel.getTodoStartDate().toDate());
        todoVO.setTodoEndDate(todoModel.getTodoEndDate().toDate());
        todoVO.setTodoCreateDate(todoModel.getTodoCreateDate().toDate());
//        System.out.println("todoVO.getTodoName() = " + todoVO.getTodoName());
        return todoVO;
    }
}
